package chapter_24.tcp.chat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator
 * Created time 2018/8/10 15:53.
 * 案例:聊天工具(服务端)
 */
public class ChatServer {

    public static void main(String[] args) {

        System.out.println("服务端运行...");

        Thread server = new Thread(() -> {

            try (// 创建一个 ServerSocket 监听端口客户请求
                 ServerSocket serverSocket = new ServerSocket(6666);
                 // 使用 accept() 阻塞等待客户端请求
                 Socket socket = serverSocket.accept();
                 DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                 DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))
            ) {

                while (true) {
                    /*
                     接收数据
                     */
                    String str = dataInputStream.readUTF();
                    // 打印接收的数据
                    System.out.printf("从客户端接收的数据: [%s] \n", str);

                    /*
                     发送数据
                     */
                    String keyboardInputStr = bufferedReader.readLine();
                    // 结束聊天
                    if (keyboardInputStr.equalsIgnoreCase("bye")) {
                        break;
                    }

                    // 发送
                    dataOutputStream.writeUTF(keyboardInputStr);
                    dataOutputStream.flush();
                }

            } catch (IOException e) {
                System.out.println("IOException");
            }

            System.out.println("服务器停止!");
        });

        server.start();
    }
}